package com.joelaws.blackberry;

import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;

public class MeetScreen extends BaseScreen {
	public MeetScreen(String thisUserId, String otherUserId) {
		this(thisUserId, otherUserId, "");
	}

	public MeetScreen(final String thisUserId, final String otherUserId,
			String action) {
		super();
		String text = getString("meet?thisUserID=" + thisUserId
				+ ":otherUserID=" + otherUserId + ":action=" + action);
		String[] data = split(text, '=');

		if (action.equals("NEVER")) {
			String loc = getLocation();
			add(new LabelField(loc));
		}

		add(new LabelField(data[0]));

		final String[] choices = split(data[1], ':');

		for (int i = 0; i < choices.length; i++) {

			final String selection = choices[i];
			if (selection.length() == 0) {
				continue;
			}
			ButtonField choice = new ButtonField(choices[i]);
			choice.setChangeListener(new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					new Thread() {
						public void run() {
							pushScreen(new MeetScreen(thisUserId, otherUserId,
									selection));
						}
					}.start();
				}
			});

			add(choice);
		}

		ButtonField choice = new ButtonField("Refresh");
		choice.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				new Thread() {
					public void run() {
						pushScreen(new MeetScreen(thisUserId, otherUserId));
					}
				}.start();
			}
		});

		add(choice);
	}

	private String getLocation() {
		final StringBuffer data = new StringBuffer();
		new Thread() {
			public void run() {
				try {
					Location location = LocationProvider.getInstance(
							new Criteria()).getLocation(5);
					if (location == null) {
						data.append("No location");
						System.out.println(data);
					} else {
						data.append(location.toString() + " "
								+ location.isValid());
						System.out.println(data);
					}
				} catch (LocationException e) {
					System.out.println(e.getMessage());
					data.append("ny");
				} catch (InterruptedException e) {
					System.out.println(e.getMessage());
					data.append("ny");
				} finally {
					synchronized (data) {
						data.notify();
					}
				}
			}
		}.start();
		synchronized (data) {
			try {
				data.wait();
			} catch (InterruptedException e) {
				System.out.println(e.getMessage());
				return e.getMessage();
			}
		}
		return data.toString();
	}
}
